# -*- coding: utf-8 -*-            
# @Author : chenliang
# @Time : 2025/7/3 09:47

import requests
from Common.get_sql_object import GetSqlObject
from Common.business_common_tool import BusinessCommonTools
from Common.excel import excel
import os


# 获取当前工作目录
current_directory = os.getcwd()
# 构造目标目录路径
target_dir = os.path.join(current_directory, "司机材料")  # 推荐使用 os.path.join 避免路径分隔符问题
# 创建目录
os.makedirs(target_dir, exist_ok=True)

# 输出路径（此时 target_dir 就是你要的路径）
print(f"成功创建或确认目录存在: {target_dir}")

# excelpath = input('目标excel文件地址:')
# folderpath = input('所有附件地址：')
# oo = excel("/Users/chenliang/Documents/浩鲸/OA/历史表单迁移/DingTalk Form Extract/HR HERE_2023.xlsx")
oo = excel("/Users/chenliang/Desktop/司机信息.xlsx")

result=oo.getExcelData('0','司机姓名','车牌号')


query_driver_list = result[0]
# sql = """SELECT
#        d.name,
#        d.phone,
#        i.license_code,
#        i.vehicle_length,
#        i.capacity,
#        i.license_type,
#        i.create_time
#    FROM
#        d_car_manage_info i
#        JOIN d_driver d ON i.user_id = d.id
#    WHERE
#         i.`status`=2
#         and DATE_FORMAT(i.create_time,'%Y-%m')='@a'
#         and d.name='杜正'
#    ORDER BY
#        i.create_time DESC"""
#
# mysql_source = GetSqlObject.get_instance("PRO")
# query_driver_list = BusinessCommonTools().get_driver('PRO', '2025-06', sql, mysql_source)

url_download = "https://driver.lxzy888.com/admin/sys/driver/downloadDriverInfo"

for i in query_driver_list:
    params = {
        "name": i[0],
    }

    headers = {
        'Content-Type': 'application/octet-stream',
        'Cookie':'SESSION=598ea828-eeac-47a7-9ba9-de92d3c682f8; imei=; rememberMe=JPWQ11jhmQd7Kn9I0fuOoX0U7pdc5GAufNdB5PlSj6s44zL17IhrUKiD4AQygPNVArXQ7shkLE1PventPEucBs6zcXm+l1YLWQ3nSyhZKURjaXantAOjL9+05UsBC68wNR/IZjRjjo6jCYeoQuaZvtcpx0lQh6y7Tr1hRXqrDNdzZZVip+jrys/8AuxHS0cxMK+wb7uCTDKE6Zu6b0yFkrMzE4pcYx+p15UOSuOKBIVFcYYwhsyqLIlPkfT4dYjMgvi4OXfpv1sF8w83g1bY2gN6OE/nQl2zj6Ns2xl6F+p47WoHsFSQzEJv6nTmySKP48eUIyRArqMaECKVovUWQvz05sehO5Y9ktbklHOg/OZxmf0IQMI+7pUp6Hw+y6cjEDkMPPfxcNpJEnT1CaXcxf43g+PcV6a3YhtEPDz+5pmvswgHbZDo4TK134Y1qac4I4EnusBdEONWeXI30hz3Ylf4dD8ScWQZkOn2XNccjMYVybDI8RESAr32WZ+fhwLx6DBOkIo/OBEw21AyQe4=',
        'Accept-Encoding':'gzip, deflate, br, zstd',
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'connection':'keep-alive'
    }

    response_down = requests.get(url=url_download, params=params,headers=headers)

    # 检查响应状态码
    if response_down.status_code == 200:
        # 确定文件名（可根据实际需求修改）
        # 方式1：手动指定文件名
        #filename = i[0]+"_"+i[1]+"_"+i[2]+".zip"  # 假设下载的是 ZIP 文件
        filename = i[0]+"_"+i[1]+".zip"  # 假设下载的是 ZIP 文件
        filename = target_dir +'/'+ filename
        print(filename)
        # 方式2：从响应头中获取文件名（如果服务器支持）
        # 例如，Content-Disposition 头可能包含文件名：
        #Content-Disposition: attachment; filename="driver_info.zip"
        content_disposition = response_down.headers.get("Content-Disposition")
        if content_disposition:
            import re

            match = re.search(r'filename="(.+)"', content_disposition)
            if match:
                filename = match.group(1)

        # 保存文件
        with open(filename, 'wb') as f:
            f.write(response_down.content)
        print(f"文件已保存为: {filename}")
    else:
        print(f"请求失败，状态码: {response_down.status_code}")
        print("响应内容:", response_down.text)



